<template>
  <view class="couponDetail">
    <view class="detailArea">
      <view class="areaA">
        <view class="amountArea price">{{ coupon.unit }}</view>
        <view class="deacArea">
          <text>{{ coupon.ruleVo }}</text>
          <view v-if="coupon.purpose === 1" class="select">
            <view>选择数量：</view>
            <u-number-box v-model="couponNum" integer button-size="20" bg-color="#fff" color="#000" :max="coupon.leftNum" :value="couponNum" @blur="changeNum" />
          </view>
          <view class="btnBuyArea" @tap="confirmBuyBtn">
            <text>{{ coupon.btnVo }}</text>
          </view>
        </view>
      </view>
      <view class="areaB">
        <view class="itemArea">
          <text class="item">可用时间：</text>
          <text class="itemDesc">{{ coupon.startTime + ' - ' + coupon.endTime }}</text>
        </view>
        <view class="itemArea">
          <text class="item">使用规则：</text>
          <text class="itemDesc">{{ coupon.rule }}</text>
        </view>
        <view class="itemArea">
          <text class="item">使用说明：</text>
          <text class="itemDesc" /><!-- 全场通用不限品类，全场通用不限品类，全场通 -->
        </view>
      </view>
      <view class="areaC">
        <view class="refoundDescArea">
          <image class="iconNotice" src="https://mm.wentsoft.com/images/icon_notice.png" /><text>该优惠券一经售出概不退货</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { wxPay2UnifiedOrder, orderCouponSave, orderCouponCancel, pointsCouponRedeem, pointsCouponGet, pointsCouponCheckPay } from '@/api/api1'
const util = require('@/utils/util')
export default {
  components: {},
  data() {
    return {
      coupon: {},
      couponNum: 1
    }
  },
  computed: {
    userInfo() {
      return this.$store.getters.userInfo
    }
  },
  onLoad(options) {
    console.log(options.coupon)
    var coupon = JSON.parse(options.coupon)
    if (coupon.purpose === 1) {
      coupon.unit = '￥' + coupon.salePrice
      coupon.ruleVo = coupon.redeemMoney + '元券 ' + coupon.rule
      coupon.btnVo = '立即买'
    } else if (coupon.purpose === 2) {
      coupon.unit = ''
      coupon.ruleVo = coupon.redeemMoney + '元券 ' + coupon.rule
      coupon.btnVo = '立即领取'
    } else if (coupon.purpose === 3) {
      coupon.unit = coupon.salePrice + '积分'
      coupon.ruleVo = coupon.redeemMoney + '元券 ' + coupon.rule
      coupon.btnVo = '立即兑换'
    }
    this.coupon = coupon
  },
  methods: {
    changeNum(e) {
      if (e.value > this.coupon.leftNum) {
        this.couponNum = this.coupon.leftNum
      }
    },
    confirmBuyBtn() {
      // 1 购买 2 领取 3 兑换
      switch (this.coupon.purpose) {
        case 1:
          this.couponPay()
          break
        case 2:
          this.couponGet()
          break
        case 3:
          this.couponRedeem()
          break
      }
    },
    async couponPay() {
      try {
        const that = this
        uni.showLoading({ title: '购买券..' })

        const finalMoney = util.accMul(that.coupon.salePrice, that.couponNum)
        const couponName = that.coupon.name
        const cardNo = that.userInfo.cardNo
        const phone = that.userInfo.phone
        const openId = that.userInfo.miniOpenid
        const storeNo = '201'// 暂时写死
        const body = '购买[' + couponName + ']*' + that.couponNum
        let payNo = null

        var params = {
          cardNo: cardNo,
          scheduleId: that.coupon.scheduleId,
          payMoney: that.coupon.salePrice,
          storeNo: storeNo,
          memo: body,
          type: that.coupon.type,
          num: that.couponNum
        }
        console.info('购买券检查参数： ', params)
        await pointsCouponCheckPay(params).then(res => {
          console.info('购买券检查返回： ', res)
          if (!res) {
            return wx.hideLoading()
          }
          payNo = res.data
          params.payNo = res.data
        })
        var unifiedOrderParam = {
          outTradeNo: payNo, // 商户订单号
          deviceInfo: storeNo, // 门店号或收银设备ID
          body: body, // 商品描述
          totalFee: util.accMul(finalMoney, 100), // 标价金额(单位为分)
          openId: openId
        }
        var requestPaymentParam = null
        await wxPay2UnifiedOrder(unifiedOrderParam).then(res => {
          console.info('统一下单返回：', res)
          requestPaymentParam = res.data.signObj
        })

        var orderParam = {
          orderNo: payNo,
          money: finalMoney,
          discountAmout: 0,
          finalMoney: finalMoney,
          mkt: storeNo,
          phone: phone,
          cardNo: cardNo,
          orderType: 'ORDER_COUPON',
          attach: JSON.stringify(params)
        }
        console.info('保存订单参数：', orderParam)
        orderCouponSave(orderParam).then(res => {
          console.info('保存订单返回：', res)
          if (!res) {
            console.info('保存订单失败')
            return wx.hideLoading()
          }
        })

        // 唤起支付
        uni.requestPayment({
          provider: 'wxpay',
          timeStamp: requestPaymentParam.timeStamp,
          nonceStr: requestPaymentParam.nonceStr,
          package: requestPaymentParam.packageObj,
          signType: requestPaymentParam.signType,
          paySign: requestPaymentParam.paySign,
          success(res) {
            console.log('success:' + JSON.stringify(res))
            console.log('微信支付成功')
          },
          fail(err) {
            console.log('fail:' + JSON.stringify(err))
            console.log('微信支付失败')
          },
          complete(res) {
            wx.hideLoading()
            console.log('complete:' + JSON.stringify(res))
            if (res.requestPayment !== 'ok') {
              orderCouponCancel({ orderNo: payNo, exceptions: res.requestPayment })
            }
            console.log('微信支付结束')
          }
        })
      } catch (error) {
        wx.hideLoading()
        console.error(error)
      }
    },
    couponGet() {
      const that = this
      const cardNo = that.userInfo.cardNo
      const storeNo = '201'// 暂时写死

      wx.showLoading({
        title: '领取券..'
      })
      pointsCouponGet({
        cardNo: cardNo,
        storeNo: storeNo,
        scheduleId: that.coupon.scheduleId,
        type: that.coupon.type,
        num: that.couponNum
      }).then(res => {
        console.info('领取券返回：', res)
        if (!res) {
          return wx.hideLoading()
        }
        wx.hideLoading()
        util.Open('提示', '券领取成功', function() {
          util.bak()
        })
      })
    },
    couponRedeem() {
      const that = this
      const couponName = that.coupon.name
      const cardNo = that.userInfo.cardNo
      const storeNo = '201'// 暂时写死
      const body = '兑换[' + couponName + ']*' + that.couponNum

      wx.showLoading({
        title: '兑换券..'
      })
      pointsCouponRedeem({
        cardNo: cardNo,
        storeNo: storeNo,
        redeemType: 1, // 兑换类别 1、积分兑换，2、积分+钱的方式兑换
        scheduleId: that.coupon.scheduleId,
        type: that.coupon.type,
        redeemPoints: that.coupon.salePrice,
        redeemAmount: 0,
        num: that.couponNum,
        memo: body
      }).then(res => {
        console.info('兑换券返回：', res)
        if (!res) {
          return wx.hideLoading()
        }
        wx.hideLoading()
        util.Open('提示', '券兑换成功', function() {
          util.bak()
        })
      })
    }
  }
}
</script>

<style lang="scss" scoped>
page {
  background: rgba(250, 250, 250, 1);
}

.detailArea {
  display: flex;
  flex-direction: column;
  background: rgba(255, 255, 255, 1);
  margin-top: 30rpx;
  margin-left: 20rpx;
  margin-right: 20rpx;
  height: 800rpx;
}

.areaA {
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 40%;
}

.areaB {
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 30%;
}

.areaC {
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 30%;
}

.amountArea {
  text-align: center;
  align-items: center;
  justify-content: center;
  margin: auto;
  font-size: 60rpx;
}

.deacArea {
  text-align: center;
  text {
    font-size: 30rpx;
    line-height: 84rpx;
    font-weight: bold;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
  .select {
    display: flex;
    justify-content: center;
    margin: 10rpx 0;
  }
}

.btnBuyArea {
  background: #2b2b2b;
  text-align: center;
  align-items: center;
  justify-content: center;
  margin: auto;
  width: 80%;
}

.btnBuyArea text {
  font-size: 24rpx;
  color: #caa95a;
  line-height: 66rpx;
}

.line {
  width: 100%;
  height: 2rpx;
  background: rgba(233, 233, 233, 1);
}

.line1 {
  width: 100%;
  height: 2rpx;
  background: rgba(233, 233, 233, 1);
  margin-top: 10rpx;
}

.item {
  font-size: 26rpx;
  color: rgba(38, 38, 38, 1);
  line-height: 74rpx;
  font-weight: bold;
}

.itemDesc {
  font-size: 24rpx;
  color: rgba(79, 76, 76, 1);
  line-height: 56rpx;
}

.itemArea {
  display: flex;
  align-items: center;
  justify-content: left;
  margin-left: 80rpx;
}

.btnRefoundArea {
  background: rgba(177, 177, 177, 1);
  border-radius: 12rpx;
  text-align: center;
  align-items: center;
  justify-content: center;
  margin: auto;
  width: 80%;
}

.btnRefoundArea text {
  font-size: 24rpx;
  color: rgba(255, 255, 255, 1);
  line-height: 66rpx;
}

.refoundDescArea {
  text-align: center;
  align-items: center;
  justify-content: center;
  margin: auto;
}

.refoundDescArea text {
  font-size: 26rpx;
  color: rgba(38, 38, 38, 1);
  line-height: 74rpx;
}

.iconNotice {
  height: 24rpx;
  width: 14rpx;
  margin-right: 10rpx;
}
.operate_box .reduce {
  font-size: 45rpx;
  margin-bottom: 10rpx;
  display: inline-block;
  width: 80rpx;
  height: 70rpx;
  line-height: 70rpx;
  text-align: center;
  border: 1px solid #dedede;
  margin-top: 25rpx;
  margin-left: 30rpx;
  border-bottom-left-radius: 8rpx;
  border-top-left-radius: 8rpx;
}
.operate_box .add {
  font-size: 45rpx;
  margin-bottom: 10rpx;
  display: inline-block;
  width: 80rpx;
  height: 70rpx;
  line-height: 70rpx;
  text-align: center;
  border: 1px solid #dedede;
  margin-top: 25rpx;
  border-bottom-right-radius: 8rpx;
  border-top-right-radius: 8rpx;
}
</style>
